import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, Select, Space, Tag, Modal, message, Descriptions, Popconfirm, Switch, Row, Col, Radio, Tooltip, Upload, Spin, Carousel } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, EnvironmentOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import moment from 'moment';
import AuthorizedButton from '@/components/Authorized/AuthorizedButton';
import SearchForm from './SearchForm';
import FacilityEditor from './FacilityEditor';
import BusinessHoursEditor from './BusinessHoursEditor';
import { request } from 'umi';

const { Option } = Select;
const { TextArea } = Input;

// 获取门店列表
const fetchStores = async (params) => {
  return request('/api/v1/store', {
    method: 'GET',
    params,
  });
};

// 获取门店详情
const fetchStoreDetail = async (id) => {
  return request(`/api/v1/store/${id}`, {
    method: 'GET',
  });
};

// 创建门店
const createStore = async (data) => {
  return request('/api/v1/store', {
    method: 'POST',
    data,
  });
};

// 更新门店
const updateStore = async (data) => {
  return request(`/api/v1/store/${data.id}`, {
    method: 'PUT',
    data,
  });
};

// 删除门店
const deleteStore = async (id) => {
  return request(`/api/v1/store/${id}`, {
    method: 'DELETE',
  });
};

// 获取城市列表
const fetchCities = async () => {
  return request('/api/v1/city', {
    method: 'GET',
    params: { pageSize: 100, status: 1 },
  });
};

// 创建城市
const createCity = async (data) => {
  return request('/api/v1/city', {
    method: 'POST',
    data,
  });
};

// 获取场地类型列表
const fetchVenueTypes = async () => {
  return request('/api/v1/venue/type', {
    method: 'GET',
  });
};

const StoreList = () => {
  const [stores, setStores] = useState([]);
  const [cities, setCities] = useState([]);
  const [venueTypes, setVenueTypes] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [storeForm] = Form.useForm();
  const [cityForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [cityFormVisible, setCityFormVisible] = useState(false);
  const [currentStore, setCurrentStore] = useState(null);
  const [headers, setHeaders] = useState({});
  const [formTitle, setFormTitle] = useState('创建门店');
  const [imageUrl, setImageUrl] = useState('');
  const [bannerUrls, setBannerUrls] = useState([]);

  // 获取门店列表
  const fetchStoreList = async () => {
    try {
      setLoading(true);
      const res = await fetchStores({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setStores(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total,
        });
      } else {
        message.error(res.message || '获取门店列表失败');
      }
    } catch (error) {
      console.error('获取门店列表出错:', error);
      message.error('获取门店列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取城市列表
  const fetchCityList = async () => {
    try {
      const res = await fetchCities();
      if (res.success) {
        setCities(res.data.list || []);
      } else {
        message.error(res.message || '获取城市列表失败');
      }
    } catch (error) {
      console.error('获取城市列表出错:', error);
      message.error('获取城市列表失败');
    }
  };

  // 获取场地类型列表
  const fetchVenueTypeList = async () => {
    try {
      const res = await fetchVenueTypes();
      if (res.success) {
        setVenueTypes(res.data || []);
      } else {
        message.error(res.message || '获取场地类型列表失败');
      }
    } catch (error) {
      console.error('获取场地类型列表出错:', error);
      message.error('获取场地类型列表失败');
    }
  };

  useEffect(() => {
    fetchStoreList();
    fetchCityList();
    fetchVenueTypeList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 查看门店详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchStoreDetail(record.id);
      if (res.success) {
        // 添加更健壮的JSON解析处理，确保banner始终是数组类型
        let banner = [];
        if (res.data.banner) {
          try {
            // 尝试解析JSON字符串
            const parsedBanner = JSON.parse(res.data.banner);
            // 确保解析结果是数组
            banner = Array.isArray(parsedBanner) ? parsedBanner : [parsedBanner];
          } catch (error) {
            // 如果解析失败，将原始字符串作为单个元素的数组
            console.error('Banner解析失败:', error);
            banner = [res.data.banner];
          }
        }
        
        setCurrentStore({
          ...res.data,
          banner: banner
        });
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取门店详情失败');
      }
    } catch (error) {
      console.error('获取门店详情出错:', error);
      message.error('获取门店详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理添加门店
  const handleAdd = () => {
    setFormTitle('创建门店');
    setCurrentStore(null);
    storeForm.resetFields();
    storeForm.setFieldsValue({
      status: true,
      facilities: [],
      banner: [],
      images: '',
    });
    // 重置图片状态
    setImageUrl('');
    setBannerUrls([]);
    setFormVisible(true);
  };

  // 处理编辑门店
  const handleEdit = (record) => {
    setFormTitle('编辑门店');
    setCurrentStore(record);
    storeForm.resetFields();
    
    // 处理banner字段，确保它是数组类型
    let bannerData = [];
    if (record.banner) {
      try {
        // 尝试解析JSON字符串
        const parsedBanner = JSON.parse(record.banner);
        // 确保解析结果是数组
        bannerData = Array.isArray(parsedBanner) ? parsedBanner : [parsedBanner];
      } catch (error) {
        // 如果解析失败，将原始字符串作为单个元素的数组
        console.error('Banner解析失败:', error);
        bannerData = record.banner ? [record.banner] : [];
      }
    }
    
    // 处理设施字段，确保它是数组类型
    let facilitiesData = [];
    if (record.facilities) {
      try {
        // 尝试解析JSON字符串
        const parsedFacilities = JSON.parse(record.facilities);
        // 确保解析结果是数组
        facilitiesData = Array.isArray(parsedFacilities) ? parsedFacilities : [];
      } catch (error) {
        // 如果解析失败，设置为空数组
        console.error('设施数据解析失败:', error);
        facilitiesData = [];
      }
    }
    
    // 处理场地类型字段，确保它是数组类型
    let venueTypesData = [];
    if (record.venue_types) {
      try {
        // 尝试解析JSON字符串
        const parsedVenueTypes = JSON.parse(record.venue_types);
        // 确保解析结果是数组
        venueTypesData = Array.isArray(parsedVenueTypes) ? parsedVenueTypes : [];
      } catch (error) {
        // 如果解析失败，设置为空数组
        console.error('场地类型数据解析失败:', error);
        venueTypesData = [];
      }
    }
    
    storeForm.setFieldsValue({
      name: record.name,
      city_id: record.city_id,
      address: record.address,
      contact_person: record.contact_person,
      phone: record.phone,
      business_hours: record.business_hours,
      description: record.description,
      notice: record.notice,
      status: record.status,
      images: record.images || '',
      banner: bannerData,
      facilities: facilitiesData,
      venue_types: venueTypesData
    });

    // 设置图片URL状态
    setImageUrl(record.images || '');
    setBannerUrls(bannerData);

    setFormVisible(true);
  };

  // 处理删除门店
  const handleDelete = async (id) => {
    try {
      setLoading(true);
      const res = await deleteStore(id);
      if (res.success) {
        message.success('删除门店成功');
        fetchStoreList();
      } else {
        message.error(res.message || '删除门店失败');
      }
    } catch (error) {
      console.error('删除门店出错:', error);
      message.error('删除门店失败');
    } finally {
      setLoading(false);
    }
  };

  // 提交表单
  const handleFormSubmit = async () => {
    try {
      const values = await storeForm.validateFields();
      setLoading(true);

      // 确保图片和轮播图数据正确
      values.images = imageUrl;
      values.banner = JSON.stringify(bannerUrls||[]);
      
      // 确保设施数据正确格式化为JSON字符串
      if (values.facilities && Array.isArray(values.facilities)) {
        values.facilities = JSON.stringify(values.facilities);
      }
      
      // 确保场地类型数据正确格式化为JSON字符串
      if (values.venue_types && Array.isArray(values.venue_types)) {
        values.venue_types = JSON.stringify(values.venue_types);
      }

      let res;
      if (currentStore) {
        // 更新
        res = await updateStore({
          id: currentStore.id,
          ...values,
        });
      } else {
        // 创建
        res = await createStore(values);
      }

      if (res.success) {
        message.success(`${currentStore ? '更新' : '创建'}门店成功`);
        setFormVisible(false);
        fetchStoreList();

        // 重置图片状态
        setImageUrl('');
        setBannerUrls([]);
      } else {
        message.error(res.message || `${currentStore ? '更新' : '创建'}门店失败`);
      }
    } catch (error) {
      console.error(`${currentStore ? '更新' : '创建'}门店出错:`, error);
      message.error(`${currentStore ? '更新' : '创建'}门店失败`);
    } finally {
      setLoading(false);
    }
  };

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.name) {
      params.name = values.name;
    }
    if (values.cityId) {
      params.cityId = values.cityId;
    }
    if (values.status !== undefined) {
      params.status = values.status;
    }

    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 表格列定义
  const columns = [
    {
      title: '门店名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
    },
    {
      title: '所在城市',
      dataIndex: 'city_id',
      key: 'city_id',
      width: 120,
      render: (city_id) => {
        const city = cities.find(c => c.id === city_id);
        return city ? city.name : '';
      },
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
      width: 200,
      ellipsis: true,
    },
    {
      title: '联系人',
      dataIndex: 'contact_person',
      key: 'contact_person',
      width: 120,
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone',
      width: 150,
    },
    {
      title: '营业时间',
      dataIndex: 'business_hours',
      key: 'business_hours',
      width: 150,
      render: (business_hours) => {
        try {
          // 尝试解析JSON字符串
          const data = JSON.parse(business_hours);
          if (data.workday && data.weekend) {
            // 简单模式显示
            const workdayText = data.workday.isOpen 
              ? `工作日: ${data.workday.openTime}-${data.workday.closeTime}` 
              : '工作日: 休息';
            
            const weekendText = data.weekend.isOpen 
              ? `周末: ${data.weekend.openTime}-${data.weekend.closeTime}` 
              : '周末: 休息';
            
            return (
              <div>
                <div>{workdayText}</div>
                <div>{weekendText}</div>
              </div>
            );
          } else if (data.daily && Array.isArray(data.daily)) {
            // 高级模式显示
            return (
              <div>
                {data.daily.map((item, index) => (
                  <div key={index}>
                    {item.dayName}: {item.isOpen ? `${item.openTime}-${item.closeTime}` : '休息'}
                  </div>
                ))}
              </div>
            );
          }
        } catch (error) {
          // 如果不是JSON格式或解析出错，直接显示原始内容
          if (typeof business_hours === 'string' && business_hours.includes('-')) {
            // 尝试处理简单的时间范围格式，如 "09:00-21:00"
            return business_hours;
          }
        }
        // 默认返回原始内容或占位符
        return business_hours || '未设置';
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '营业中' : '暂停营业'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (created_at) => moment(created_at * 1000).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <AuthorizedButton
            permission="store:update"
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </AuthorizedButton>
          <Popconfirm
            title="确定要删除此门店吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <AuthorizedButton
              permission="store:delete"
              type="link"
              icon={<DeleteOutlined />}
              danger
            >
              删除
            </AuthorizedButton>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };


  // 处理添加城市
  function handleAddCity() {
    cityForm.resetFields();
    setCityFormVisible(true);
  }

  return (
    <PageContainer>
      <Card
        title="门店管理"
        extra={
          <Space>
            <AuthorizedButton permission="store:create" type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              创建门店
            </AuthorizedButton>
          </Space>
        }
      >
        <SearchForm
          onSearch={handleSearch}
          onReset={handleReset}
          cities={cities}
        />

        <Table
          columns={columns}
          dataSource={stores}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1100 }}
        />
      </Card>

      {/* 门店详情弹窗 */}
      <Modal
        title="门店详情"
        visible={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={700}
      >
        {currentStore && (
          <Descriptions bordered column={2}>
            <Descriptions.Item label="门店名称" span={2}>{currentStore.name}</Descriptions.Item>
            <Descriptions.Item label="所在城市">{cities.find(c => c.id === currentStore.city_id)?.name || '未知城市'}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={currentStore.status === 1 ? 'green' : 'red'}>
                {currentStore.status === 1 ? '营业中' : '暂停营业'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="地址" span={2}>{currentStore.address}</Descriptions.Item>
            <Descriptions.Item label="联系人">{currentStore.contact_person}</Descriptions.Item>
            <Descriptions.Item label="联系电话">{currentStore.phone}</Descriptions.Item>
            <Descriptions.Item label="营业时间" span={2}>
              {(() => {
                try {
                  const businessHours = JSON.parse(currentStore.business_hours);
                  if (businessHours.workday && businessHours.weekend) {
                    const workdayText = businessHours.workday.isOpen 
                      ? `工作日: ${businessHours.workday.openTime}-${businessHours.workday.closeTime}` 
                      : '工作日: 休息';
                    
                    const weekendText = businessHours.weekend.isOpen 
                      ? `周末: ${businessHours.weekend.openTime}-${businessHours.weekend.closeTime}` 
                      : '周末: 休息';
                    
                    return (
                      <div>
                        <div>{workdayText}</div>
                        <div>{weekendText}</div>
                      </div>
                    );
                  }
                  return currentStore.business_hours;
                } catch (error) {
                  return currentStore.business_hours;
                }
              })()}
            </Descriptions.Item>
            <Descriptions.Item label="门店描述" span={2}>{currentStore.description}</Descriptions.Item>
            <Descriptions.Item label="弹窗通知" span={2}>{currentStore.notice}</Descriptions.Item>
            <Descriptions.Item label="门店设施" span={2}>
              {currentStore.facilities ? (
                <div className="facility-tags">
                  {(() => {
                    try {
                      const facilities = JSON.parse(currentStore.facilities);
                      return Array.isArray(facilities) && facilities.length > 0 ? (
                        facilities.map((facility, index) => (
                          <Tag key={index} style={{ margin: '0 8px 8px 0' }}>{facility}</Tag>
                        ))
                      ) : '暂无设施';
                    } catch (error) {
                      console.error('解析设施数据失败:', error);
                      return '暂无设施';
                    }
                  })()} 
                </div>
              ) : '暂无设施'}
            </Descriptions.Item>
            <Descriptions.Item label="场地类型" span={2}>
              {currentStore.venue_types ? (
                <div className="venue-type-tags">
                  {(() => {
                    try {
                      const types = JSON.parse(currentStore.venue_types);
                      return Array.isArray(types) && types.length > 0 ? (
                        types.map((typeId) => {
                          const type = venueTypes.find(t => t.id === typeId);
                          return type ? (
                            <Tag key={typeId} style={{ margin: '0 8px 8px 0' }}>{type.name}</Tag>
                          ) : null;
                        })
                      ) : '暂无场地类型';
                    } catch (error) {
                      console.error('解析场地类型数据失败:', error);
                      return '暂无场地类型';
                    }
                  })()}
                </div>
              ) : '暂无场地类型'}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{moment(currentStore.created_at * 1000).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
            {currentStore.images && (
              <Descriptions.Item label="门店图片" span={2}>
                <img src={currentStore.images} alt="门店图片" style={{ maxWidth: '100%', maxHeight: '200px' }} />
              </Descriptions.Item>
            )}
            {currentStore.banner && currentStore.banner.length > 0 && (
              <Descriptions.Item label="轮播图" span={2}>
                <Row gutter={[16, 16]}>
                  {Array.isArray(currentStore.banner) ? (
                    currentStore.banner.map((url, index) => (
                      <Col span={8} key={index}>
                        <div style={{ width: '100%', height: '150px', overflow: 'hidden', borderRadius: '4px' }}>
                          <img 
                            src={url} 
                            alt={`轮播图${index + 1}`} 
                            style={{ width: '100%', height: '100%', objectFit: 'cover' }} 
                          />
                        </div>
                      </Col>
                    ))
                  ) : (
                    <Col span={8}>
                      <div style={{ width: '100%', height: '150px', overflow: 'hidden', borderRadius: '4px' }}>
                        <img 
                          src={currentStore.banner} 
                          alt="轮播图" 
                          style={{ width: '100%', height: '100%', objectFit: 'cover' }} 
                        />
                      </div>
                    </Col>
                  )}
                </Row>
              </Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>
      {/* 门店表单弹窗 */}
      <Modal
        title={formTitle}
        visible={formVisible}
        onCancel={() => setFormVisible(false)}
        footer={null}
        width={700}
        destroyOnClose
      >
        <Form
          form={storeForm}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleFormSubmit}
        >
          <Form.Item label="门店名称" name="name" rules={[{ required: true, message: '请输入门店名称' }]}>
            <Input placeholder="请输入门店名称" />
          </Form.Item>
          <Form.Item label="所在城市" name="city_id" rules={[{ required: true, message: '请选择城市' }]}>
            <Select placeholder="请选择城市" allowClear>
              {cities.map(city => (
                <Option key={city.id} value={city.id}>{city.name}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="状态" name="status" rules={[{ required: true, message: '请选择状态' }]}>
            <Select placeholder="请选择状态">
              <Option value={1}>营业中</Option>
              <Option value={0}>暂停营业</Option>
            </Select>
          </Form.Item>
          <Form.Item label="地址" name="address" rules={[{ required: true, message: '请输入地址' }]}>
            <Input placeholder="请输入地址" />
          </Form.Item>
          <Form.Item label="联系人" name="contact_person" rules={[{ required: true, message: '请输入联系人' }]}>
            <Input placeholder="请输入联系人" />
          </Form.Item>
          <Form.Item label="联系电话" name="phone" rules={[{ required: true, message: '请输入联系电话' }]}>
            <Input placeholder="请输入联系电话" />
          </Form.Item>
          <Form.Item label="营业时间" name="business_hours" rules={[{ required: true, message: '请设置营业时间' }]}>
            <BusinessHoursEditor />
          </Form.Item>
          <Form.Item label="门店描述" name="description">
            <Input.TextArea placeholder="请输入门店描述" />
          </Form.Item>
          <Form.Item label="弹窗通知" name="notice">
            <Input.TextArea placeholder="请输入弹窗通知" />
          </Form.Item>
          <Form.Item label="门店设施" name="facilities">
            <FacilityEditor />
          </Form.Item>
          <Form.Item label="场地类型" name="venue_types">
            <Select
              mode="multiple"
              placeholder="请选择场地类型"
              style={{ width: '100%' }}
              optionFilterProp="label"
            >
              {venueTypes.map(type => (
                <Option key={type.id} value={type.id} label={type.name}>
                  {type.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="门店图片" name="images">
            <Upload
              listType="picture-card"
              action="/api/v1/upload"
              beforeUpload={(file) => {
                const isImage = file.type.startsWith('image/');
                if (!isImage) {
                  message.error('只能上传图片文件');
                }
                const token = localStorage.getItem('token');
                const authHeader = { Authorization: 'Bearer ' + token };
                setHeaders(authHeader);
                return isImage;
              }}
              customRequest={async ({ file, onSuccess, onError }) => {
                try {
                  const formData = new FormData();
                  formData.append('file', file);

                  const res = await fetch('/api/v1/upload', {
                    method: 'POST',
                    headers: {
                      Authorization: `Bearer ${localStorage.getItem('token')}`
                    },
                    body: formData
                  });
                  console.log("res:", res);
                  const data = await res.json();
                  console.log("data:", data);

                  if (data.success) {
                    setLoading(false);
                    const url = data.data;
                    if (url) {
                      storeForm.setFieldsValue({
                        imageUrl: url,
                      });
                      setImageUrl(url);
                    }
                  } else {
                    message.error('上传失败，请重试：' + data.message);
                  }

                  // 构造符合组件要求的响应对象
                  onSuccess({
                    status: 'success',
                    url: data.data, // 使用后端返回的URL
                    response: data
                  }, file);

                } catch (err) {
                  onError(err);
                }
              }}
              onChange={(info) => {
                console.log("onChange:", info);
                if (info.file.status === 'uploading') {
                  setLoading(true);
                }
              }}
              headers={headers}
              maxCount={1}
              showUploadList={{ showPreviewIcon: false }}
              disabled={loading}
              fileList={imageUrl ? [{ url: imageUrl }] : []}
            >
              {imageUrl ? null : loading ? <Spin /> : <PlusOutlined />}
            </Upload>
          </Form.Item>
          <Form.Item label="门店轮播图" name="banner">
            <Upload
              listType="picture-card"
              action="/api/v1/upload/multi"
              beforeUpload={(file) => {
                const isImage = file.type.startsWith('image/');
                if (!isImage) {
                  message.error('只能上传图片文件');
                }
                const token = localStorage.getItem('token');
                const authHeader = { Authorization: 'Bearer ' + token };
                setHeaders(authHeader);
                return isImage;
              }}
              customRequest={async ({ file, onSuccess, onError }) => {
                try {
                  console.log("customRequest:", file);
                  const formData = new FormData();
                  formData.append('files', file);

                  const res = await fetch('/api/v1/upload/multi', {
                    method: 'POST',
                    headers: {
                      Authorization: `Bearer ${localStorage.getItem('token')}`
                    },
                    body: formData
                  });
                  console.log("res:", res);
                  const data = await res.json();
                  console.log("data:", data);
                  if (data.success) {
                    setLoading(false);
                    const urls = data.data;
                    if (urls && urls.length > 0) {
                      setBannerUrls([...bannerUrls, ...urls]);
                    }
                  } else {
                    message.error('上传失败，请重试：' + data.message);
                  }
                  // 构造符合组件要求的响应对象
                  onSuccess({
                    status:'success',
                    url: data.data, // 使用后端返回的URL
                    response: data
                  }, file);

                } catch (err) {
                  onError(err);
                }
              }}
              onChange={(info) => {
                if (info.file.status === 'uploading') {
                  setLoading(true);
                  return;
                }
              }}
              headers={headers}
              maxCount={5}
              showUploadList={{ showPreviewIcon: false }}
              disabled={loading}
              fileList={bannerUrls.map(url => ({ url }))}
              onRemove={(file) => {
                const index = bannerUrls.indexOf(file.url);
                if (index !== -1) {
                  bannerUrls.splice(index, 1);
                  setBannerUrls([...bannerUrls]);
                }
              }}
            >
              {loading ? <Spin /> : <PlusOutlined />}
            </Upload>
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="link" onClick={handleAddCity}>新增城市</Button>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button onClick={() => setFormVisible(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 城市表单弹窗 */}
      <Modal
        title="新增城市"
        visible={cityFormVisible}
        onCancel={() => setCityFormVisible(false)}
        footer={null}
        width={500}
        destroyOnClose
      >
        <Form
          form={cityForm}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          onFinish={async (values) => {
            try {
              setLoading(true);
              const res = await createCity(values);
              if (res.success) {
                message.success('创建城市成功');
                setCityFormVisible(false);
                fetchCityList(); // 刷新城市列表
                cityForm.resetFields();
              } else {
                message.error(res.message || '创建城市失败');
              }
            } catch (error) {
              console.error('创建城市出错:', error);
              message.error('创建城市失败');
            } finally {
              setLoading(false);
            }
          }}
        >
          <Form.Item label="城市名称" name="name" rules={[{ required: true, message: '请输入城市名称' }]}>
            <Input placeholder="请输入城市名称" />
          </Form.Item>
          <Form.Item label="排序" name="sort" initialValue={0}>
            <Input type="number" placeholder="请输入排序值" />
          </Form.Item>
          <Form.Item label="状态" name="status" initialValue={1}>
            <Radio.Group>
              <Radio value={1}>启用</Radio>
              <Radio value={0}>禁用</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                提交
              </Button>
              <Button onClick={() => setCityFormVisible(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );

};
export default StoreList;